<template>
  <!-- 专利趋势分析(新设计包含总量，实用新型，发明专利) -->
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :param="param"
          :tname="tname"
          :leftTreeParentId="leftTreeParentId"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
        <div class="right-tools">
          <span
            @click="handleShowContrastive"
            v-if="tname == '申请人趋势分析' || tname == '发明人趋势分析'"
            >对比分析</span
          >
        </div>
      </template>
      <template slot="chart">
        <ChartR
          v-if="datatype !== -1"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @domRef="getDomRef"
          @contrastiveData="getContrastiveData"
        />
        <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">&nbsp;保存图片</i>
        <i class="icon el-icon-full-screen" @click="handleFullScreen">&nbsp;全屏</i>
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p style="flex: none; width: 30px"></p>
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p style="flex: none; width: 30px">
            <el-checkbox
              v-model="checkList[index]"
              :key="index"
              @change="handleChangeCheck"
              >&nbsp;</el-checkbox
            >
          </p>
          <p v-for="(ite, j) in item" :key="j">
            <span
              v-if="!tableData.inputRefs[index][j]"
              @click="handleClick(ite)"
              >{{ ite }}</span
            >
            <span v-else>
              <el-input
                v-model="tableData._content[index][j]"
                placeholder=""
                size="mini"
                :style="{'min-width': tableData._content[index][j].length >= 10 ? '230px' : '100px'}"
              ></el-input>
            </span>
            <span v-if="j != 0" class="tools-box">
              <!-- 修改 -->
              <i
                v-if="!tableData.inputRefs[index][j]"
                class="tools-btn el-icon-edit"
                @click="handleShowInp(index, j)"
              ></i>
              <!-- 保存 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-check"
                @click="handleUpdateIte(index, j)"
              ></i>
              <!-- 取消 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-close"
                @click="handleShowInp(index, j)"
              ></i>
            </span>
          </p>
        </li>
      </ul>
    </div>

    <!-- 对比分析 -->
    <Contrastive ref="contrastive" />
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartR from "../charts/ChartR";
import {
  refactor,
  getYear,
  downloadChartImg,
  transCNCountry,
  isShowContrastBtn
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import Contrastive from "../Contrastive";
import ChooseScreen from "./chooseScreen.vue";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object
    },
    dcData: {
      type: Object
    }
  },
  components: {
    CSlot,
    ChartR,
    Contrastive,
    ChooseScreen
  },
  data() {
    return {
      searchTxt: "",
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      charttype: -1, // 图表类型
      selectATit: "", // 筛选条件B，动态
      timeType: "isd", // 设置时间筛选类型
      chartId: "", // 图表id名称
      datatype: -1, // 图表数据类型
      chartData: {},
      _chartData: {},
      chartType: "line",
      dom: {},
      domRef: null, // 记录图表dom对象，用于全屏
      tableData: {
        tit: ["年份", "总量", "发明专利", "实用新型"],
        content: [],
        _content: [], // 存储修改content值
        inputRefs: [] // 记录修改展示的input的值
      },
      checkList: [], // 多选框勾选数据
      yearArr: [],
      contrastiveData: [], // 对比分析的数据
      emptyText: "数据加载中...",
      dbid: "",
      timeType: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: "", // startYear
      datefieldformatTxt2: "",  // endYear
      msq: "",
      leftTreeParentId: 0
    };
  },
  computed: {
    ...mapState(["searchWord"])
  },
  watch: {
    // chartTempl() {
    //   this.init();
    // },
    dcData(newv) {
      this.init();
    }
  },
  mounted() {
    this.dbid = String(this.$route.query.type);
    // this.init();
  },
  methods: {
    init() {
      this.leftTreeParentId = this.chartTempl.parentId;
      this.tname = this.chartTempl.tname;
      this.param = this.chartTempl.tdata.param;
      this.charttype = this.chartTempl.tdata.charttype;
      this.chartId = "chart" + this.chartTempl.id;
      this.datatype = this.chartTempl.tdata.datatype;
      this.timeType = this.chartTempl.tdata.datefield;
      this.datefieldformat = this.chartTempl.tdata.datefieldformat;
      this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
      this.datefieldformatTxt2 = this.datefieldformat == 1 ? "-12-31" : "";
      this.tableData.content = [];
      this.tableData._content = [];
      this.tableData.inputRefs = [];
      if (this.dcData && this.dcData.aggs && this.dcData.aggs.apd) {
        this.chartData = JSON.parse(JSON.stringify(this.dcData.aggs));
        this.loading = false;
        this._chartData = JSON.parse(JSON.stringify(this.dcData.aggs));
        this.tableData.content = [];
        this.checkList = [];
        this.chartData.apd.map((it, index) => {
          this.tableData.content.push([
            it.key,
            it.doc_count,
            it.na[0]?.doc_count,
            it.na[1]?.doc_count
          ]);
          this.tableData._content.push([
            it.key,
            it.doc_count,
            it.na[0]?.doc_count,
            it.na[1]?.doc_count
          ]);
          this.checkList.push(true);
        });
        // 记录inputRefs
        this.tableData.content.forEach(v => {
          let boo = [];
          v.map(b => {
            boo.push(false);
          });
          this.tableData.inputRefs.push(boo);
        });
      } 
      this.handleParams();
    },
    // 修改表格文字内容
    handleUpdateIte(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请勾选后再进行修改"
        });
        return;
      }
      this.$set(
        this.tableData.content[index],
        j,
        this.tableData._content[index][j]
      );
      this.handleShowInp(index, j);
      // 重新设置chartData数据
      let chartData = JSON.parse(JSON.stringify(this.chartData));
      if (j == 1) {
        chartData.apd[index]["doc_count"] = this.tableData.content[index][j];
      } else {
        chartData.apd[index].na[j - 2]["doc_count"] = this.tableData.content[
          index
        ][j];
        chartData.apd[index]["doc_count"] =
          Number(this.tableData.content[index][2]) +
          Number(this.tableData.content[index][3]);
        this.tableData.content[index][1] =
          Number(this.tableData.content[index][2]) +
          Number(this.tableData.content[index][3]);
      }
      this.chartData = chartData;
    },
    // 显隐修改表格文字input框
    handleShowInp(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请选勾选后再进行修改"
        });
        return;
      }
      if (this.tableData.inputRefs[index][j] === true) {
        this.$set(this.tableData.inputRefs[index], j, false);
      } else {
        this.$set(this.tableData.inputRefs[index], j, true);
      }
    },
    // 勾选
    handleChangeCheck() {
      // let chartData = JSON.parse(JSON.stringify(this.chartData));
      let arr= [];
      this.checkList.forEach((v, index) => {
        // let type = this.tableData.content[index][0];
        if (v == true) {
          arr.push(this._chartData.apd[index]);
          // if (type === "申请趋势") {
          //   chartData.apd[index] = this._chartData.apd[index];
          // } else if (type === "公开趋势") {
          //   let apdArr = this.tableData.content.filter(
          //     b => b[0] === "申请趋势"
          //   );
          //   let isd_index = index - apdArr.length; // 这里用来获取公开趋势对应的chartData的index，需要减去前面申请趋势的index
          //   chartData.isd[isd_index] = this._chartData.isd[isd_index];
          // }
        }
      });
      this.chartData["apd"] = arr;
    },
    // 拼装sq 给对比分析使用
    handleParams() {
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=2012${this.datefieldformatTxt} AND ${this.timeType}<=2022${this.datefieldformatTxt2}`;
      let sq1 = `isd>=2012${this.datefieldformatTxt} AND isd<=2022${this.datefieldformatTxt2}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq + " AND " + sq1;
      }
      this.msq = sq;
    },
    getChartData(Params) {
      if (this.cancel !== null) {
        this.cancel();
      }
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=${Params.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${Params.endYear}${this.datefieldformatTxt2}`;
      let sq1 = `isd>=${Params.startYear}${this.datefieldformatTxt} AND isd<=${Params.endYear}${this.datefieldformatTxt2}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq + " AND " + sq1;
      }
      this.msq = sq;
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = {};
      this.tableData = {
        tit: [],
        content: [],
        _content: [],
        inputRefs: []
      };
      let params = {
        aggs: this.chartTempl.tdata.param.aggs,
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 1,
        rSearch: "",
        smartSearch: "",
        sort: []
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      let familyFlag = localStorage.getItem("familyFlag") || false;
      if (familyFlag ==1 ) {
        params["familyFlag"] = true; // 同族合并
        params["tzzlhb"] = false; // 同专利合并
      } else if (familyFlag ==2) {
        params["familyFlag"] = false; // 同族合并
        params["tzzlhb"] = true; // 同专利合并
      }
      let ths = this;
      this.$post(this.$Url.search.patentAggsTrends, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
        })
      })
        .then(res => {
          this.chartData = JSON.parse(JSON.stringify(res.data.aggs));
          this.$store.commit("setTotalTxt", res.data.total);
          this.loading = false;
          this.tableData.content = [];
          this.chartData.apd.map((it, index) => {
            this.tableData.content.push([
              it.key,
              it.doc_count,
              it.na[0]?.doc_count,
              it.na[1]?.doc_count
            ]);
            this.tableData._content.push([
              it.key,
              it.doc_count,
              it.na[0]?.doc_count,
              it.na[1]?.doc_count
            ]);
          });
            // 记录inputRefs
        this.tableData.content.forEach(v => {
          let boo = [];
          v.map(b => {
            boo.push(false);
          });
          this.tableData.inputRefs.push(boo);
        });
        })
        .catch(err => {
          this.emptyText = "暂无数据";
          this.loading = false;
        });
    },
    getDomRef(dom) {
      this.domRef = dom
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    // 全屏
    handleFullScreen() {
      let element = this.domRef
      if (!element) {
        return
      }
      // 全屏查看
      if (element.requestFullScreen) {
        // HTML W3C 提议
        element.requestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        // Webkit
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      }
      // 退出全屏
      if (element.requestFullScreen) {
        document.exitFullscreen();
      } else if (element.msRequestFullScreen) {
        document.msExitFullscreen();
      } else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
      } else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
      }
    },
    // 保存图片
    downloadImg() {
      downloadChartImg(this.dom);
    },

    // 对比分析
    getContrastiveData(data) {
      this.contrastiveData = data;
    },
    handleShowContrastive() {
      if (this.contrastiveData.length <= 0) {
        this.$message.warning("请至少选择一项数据！");
        return;
      }
      this.$refs.contrastive.init(
        this.contrastiveData,
        this.chartTempl,
        this.dbid,
        this.msq
      );
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws = XLSX.utils.aoa_to_sheet(
        aoa
      ); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    }
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  }
};
</script>

<style lang="scss"></style>
